package com.leefine.nettysocketproxy.support;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leefine.nettysocketproxy.proxy.SocketProxyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.List;

/**
 * SocketProxyServerJsonUtil
 *
 * @Author lihuai.chen@163.com
 * @Date 6/10/2021 10:37 AM
 */
public class SocketProxyServerJsonUtil {
    private final static Logger logger = LoggerFactory.getLogger(SocketProxyServerJsonUtil.class);
    private static Object jsonFileLock = new Object();

    public static List<SocketProxyServer> serverList() {
        synchronized (jsonFileLock) {
            List<SocketProxyServer> serverList = null;
            try {
                ObjectMapper objectMapper = new ObjectMapper();

                File file = new File(Util.getRootPath() + "server.json");
                if (file.exists())
                    serverList = objectMapper.readValue(file, new TypeReference<List<SocketProxyServer>>() {
                    });
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
            return serverList;
        }
    }

    public static boolean saveList(List<SocketProxyServer> serverList) {
        synchronized (jsonFileLock) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                File file = new File(Util.getRootPath() + "server.json");
                objectMapper.writeValue(file, serverList);
                logger.info("update server.json");
            } catch (Exception e) {
                logger.error(e.getMessage());
                return false;
            }
            return true;
        }
    }
}